package com.scheduling.order.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scheduling.order.entity.Customer;
import com.scheduling.order.entity.Order;
import com.scheduling.order.entity.dto.OrderDTO;
import com.scheduling.order.entity.dto.OrderItemDTO;
import com.scheduling.order.mapper.CustomerMapper;
import com.scheduling.order.mapper.OrderItemMapper;
import com.scheduling.order.mapper.OrderMapper;
import com.scheduling.order.service.IOrderItemService;
import com.scheduling.order.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

/**
 * 订单服务实现类
 *
 * @author 开发团队
 * @since 2025-05-29
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    private final CustomerMapper customerMapper;
    private final OrderItemMapper orderItemMapper;
    private final IOrderItemService orderItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO createOrder(OrderDTO orderDTO) {
        log.info("创建订单: {}", orderDTO);

        // 1. 处理客户信息
        String customerId = handleCustomer(orderDTO);

        // 2. 创建订单
        Order order = new Order();
        order.setCustomerId(customerId);
        order.setDueDate(orderDTO.getDueDate());
        order.setStatus(Order.OrderStatus.PENDING);

        boolean orderSaved = this.save(order);
        if (!orderSaved) {
            throw new RuntimeException("订单保存失败");
        }

        // 3. 创建订单项
        List<OrderItemDTO> orderItems = orderItemService.createOrderItems(order.getOrderId(), orderDTO.getOrderItems());

        // 4. 返回订单详情
        OrderDTO result = this.getOrderDetail(order.getOrderId());
        log.info("订单创建成功，订单ID: {}", order.getOrderId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderDTO updateOrder(OrderDTO orderDTO) {
        log.info("更新订单: {}", orderDTO.getOrderId());

        if (StrUtil.isBlank(orderDTO.getOrderId())) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        // 1. 检查订单是否存在
        Order existingOrder = this.getById(orderDTO.getOrderId());
        if (existingOrder == null) {
            throw new RuntimeException("订单不存在: " + orderDTO.getOrderId());
        }

        // 2. 处理客户信息
        String customerId = handleCustomer(orderDTO);

        // 3. 更新订单
        Order order = new Order();
        order.setOrderId(orderDTO.getOrderId());
        order.setCustomerId(customerId);
        order.setDueDate(orderDTO.getDueDate());

        boolean orderUpdated = this.updateById(order);
        if (!orderUpdated) {
            throw new RuntimeException("订单更新失败");
        }

        // 4. 删除原有订单项，重新创建
        orderItemService.deleteOrderItemsByOrderId(orderDTO.getOrderId());
        orderItemService.createOrderItems(orderDTO.getOrderId(), orderDTO.getOrderItems());

        // 5. 返回订单详情
        OrderDTO result = this.getOrderDetail(orderDTO.getOrderId());
        log.info("订单更新成功: {}", orderDTO.getOrderId());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteOrder(String orderId) {
        log.info("删除订单: {}", orderId);

        if (StrUtil.isBlank(orderId)) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        // 1. 删除订单项
        int deletedItems = orderItemService.deleteOrderItemsByOrderId(orderId);
        log.info("删除订单项数量: {}", deletedItems);

        // 2. 删除订单
        boolean orderDeleted = this.removeById(orderId);
        if (!orderDeleted) {
            throw new RuntimeException("订单删除失败");
        }

        log.info("订单删除成功: {}", orderId);
        return true;
    }

    @Override
    public OrderDTO getOrderDetail(String orderId) {
        if (StrUtil.isBlank(orderId)) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        // 查询订单基础信息（包含客户信息）
        OrderDTO orderDTO = baseMapper.selectOrderDTOById(orderId);
        if (orderDTO == null) {
            throw new RuntimeException("订单不存在，订单ID: " + orderId);
        }

        // 查询订单项
        List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(orderId);
        orderDTO.setOrderItems(orderItems);

        // 计算统计信息
        calculateOrderStatistics(orderDTO);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> getOrderPage(long current, long size, String customerName, String status,
                                       LocalDate startDate, LocalDate endDate) {
        Page<OrderDTO> page = new Page<>(current, size);
        Page<OrderDTO> result = baseMapper.selectOrderDTOPage(page, customerName, status, startDate, endDate);

        // 为每个订单添加统计信息
        result.getRecords().forEach(orderDTO -> {
            List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(orderDTO.getOrderId());
            orderDTO.setOrderItems(orderItems);
            calculateOrderStatistics(orderDTO);
        });

        return result;
    }

    @Override
    public List<OrderDTO> getOrdersByStatus(String status) {
        List<OrderDTO> orders = baseMapper.selectOrderDTOsByStatus(status);

        // 为每个订单添加订单项和统计信息
        orders.forEach(orderDTO -> {
            List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(orderDTO.getOrderId());
            orderDTO.setOrderItems(orderItems);
            calculateOrderStatistics(orderDTO);
        });

        return orders;
    }

    @Override
    public List<OrderDTO> getOverdueOrders() {
        List<OrderDTO> orders = baseMapper.selectOverdueOrderDTOs();

        // 为每个订单添加订单项和统计信息
        orders.forEach(orderDTO -> {
            List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(orderDTO.getOrderId());
            orderDTO.setOrderItems(orderItems);
            calculateOrderStatistics(orderDTO);
        });

        return orders;
    }

    @Override
    public boolean updateOrderStatus(String orderId, String status) {
        if (StrUtil.isBlank(orderId)) {
            throw new IllegalArgumentException("订单ID不能为空");
        }

        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Order::getOrderId, orderId)
                .set(Order::getStatus, status);

        boolean updated = this.update(updateWrapper);
        if (updated) {
            log.info("订单状态更新成功: {} -> {}", orderId, status);
        }

        return updated;
    }

    @Override
    public void updateOrderStatusByItems(String orderId) {
        List<OrderItemDTO> orderItems = orderItemService.getOrderItemsByOrderId(orderId);

        if (orderItems.isEmpty()) {
            return;
        }

        // 统计订单项状态
        long totalItems = orderItems.size();
        long completedItems = orderItems.stream()
                .filter(item -> Order.OrderStatus.COMPLETED.equals(item.getStatus()))
                .count();
        long inProductionItems = orderItems.stream()
                .filter(item -> Order.OrderStatus.IN_PRODUCTION.equals(item.getStatus()))
                .count();

        // 根据订单项状态决定订单状态
        String newStatus;
        if (completedItems == totalItems) {
            newStatus = Order.OrderStatus.COMPLETED;
        } else if (inProductionItems > 0 || completedItems > 0) {
            newStatus = Order.OrderStatus.IN_PRODUCTION;
        } else {
            newStatus = Order.OrderStatus.PENDING;
        }

        this.updateOrderStatus(orderId, newStatus);
    }

    @Override
    public void refreshOrderProgress(String orderId) {
        // 重新计算订单状态
        this.updateOrderStatusByItems(orderId);

        log.info("订单进度刷新完成: {}", orderId);
    }

    @Override
    public List<OrderDTO> getPendingOrders() {
        return this.getOrdersByStatus(Order.OrderStatus.PENDING);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchUpdateOrderStatus(List<String> orderIds, String status) {
        if (orderIds == null || orderIds.isEmpty()) {
            return 0;
        }

        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Order::getOrderId, orderIds)
                .set(Order::getStatus, status);

        boolean updated = this.update(updateWrapper);
        int updatedCount = updated ? orderIds.size() : 0;

        log.info("批量更新订单状态: {} 个订单 -> {}", updatedCount, status);
        return updatedCount;
    }

    /**
     * 处理客户信息（如果客户不存在则创建）
     */
    private String handleCustomer(OrderDTO orderDTO) {
        String customerId = orderDTO.getCustomerId();

        // 如果有客户ID，先检查客户是否存在
        if (StrUtil.isNotBlank(customerId)) {
            Customer existingCustomer = customerMapper.selectById(customerId);
            if (existingCustomer != null) {
                // 更新客户信息
                existingCustomer.setCustomerName(orderDTO.getCustomerName());
                existingCustomer.setCustomerContact(orderDTO.getCustomerContact());
                customerMapper.updateById(existingCustomer);
                return customerId;
            }
        }

        // 根据客户名称查找客户
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Customer::getCustomerName, orderDTO.getCustomerName());
        Customer existingCustomer = customerMapper.selectOne(queryWrapper);

        if (existingCustomer != null) {
            // 更新客户联系方式
            existingCustomer.setCustomerContact(orderDTO.getCustomerContact());
            customerMapper.updateById(existingCustomer);
            return existingCustomer.getCustomerId();
        }

        // 创建新客户
        Customer newCustomer = new Customer();
        newCustomer.setCustomerName(orderDTO.getCustomerName());
        newCustomer.setCustomerContact(orderDTO.getCustomerContact());

        int inserted = customerMapper.insert(newCustomer);
        if (inserted <= 0) {
            throw new RuntimeException("客户创建失败");
        }

        log.info("创建新客户: {} - {}", newCustomer.getCustomerName(), newCustomer.getCustomerId());
        return newCustomer.getCustomerId();
    }

    /**
     * 计算订单统计信息
     */
    private void calculateOrderStatistics(OrderDTO orderDTO) {
        List<OrderItemDTO> orderItems = orderDTO.getOrderItems();
        if (orderItems == null || orderItems.isEmpty()) {
            return;
        }

        // 计算总数量和已完成数量
        int totalQuantity = orderItems.stream()
                .mapToInt(OrderItemDTO::getQuantity)
                .sum();
        int completedQuantity = orderItems.stream()
                .mapToInt(item -> item.getProducedQuantity() != null ? item.getProducedQuantity() : 0)
                .sum();

        // 计算完成率
        double completionRate = totalQuantity > 0 ?
                Math.round((completedQuantity * 100.0 / totalQuantity) * 100.0) / 100.0 : 0.0;

        orderDTO.setTotalQuantity(totalQuantity);
        orderDTO.setCompletedQuantity(completedQuantity);
        orderDTO.setCompletionRate(completionRate);
    }
} 